//dataTables js 重新封装
define(["require","jquery","notify_comm","String"],function(require,$,notify_comm,String){

    var default_btn_event = [];//需要绑定事件的默认按钮

    //语言设置
    var _language = {
        zh_CN: function(){
            var language = {
                sEmptyTable: "列表数据为空",
                sInfo: "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
                sInfoEmpty: "显示第 0 至 0 项结果，共 0 项",
                sInfoFiltered: "(由 _MAX_ 项结果过滤)",
                sInfoPostFix: "",
                sInfoThousands: ",",
                sLengthMenu: "显示 _MENU_ 项结果",
                sLoadingRecords: "载入中...",
                sProcessing: "处理中...",
                sSearch: "搜索:",
                sZeroRecords: "没有匹配结果",
                oPaginate: {
                    sFirst: "首页",
                    sPrevious: "上一页",
                    sNext: "下一页",
                    sLast: "末页"
                },
                oAria: {
                    sSortAscending: ": 以升序排列此列",
                    sSortDescending: ": 以降序排列此列"
                }
            }
            return language;
        },
        en_US: function(){
            var language = {
                emptyTable:     "No data available in table",
                info:           "Showing _START_ to _END_ of _TOTAL_ entries",
                infoEmpty:      "Showing 0 to 0 of 0 entries",
                infoFiltered:   "(filtered from _MAX_ total entries)",
                infoPostFix:    "",
                thousands:      ",",
                lengthMenu:     "Show _MENU_ entries",
                loadingRecords: "Loading...",
                processing:     "Processing...",
                search:         "Search:",
                zeroRecords:    "No matching records found",
                paginate: {
                    first:      "First",
                    last:       "Last",
                    next:       "Next",
                    previous:   "Previous"
                },
                aria: {
                    sortAscending:  ": activate to sort column ascending",
                    sortDescending: ": activate to sort column descending"
                }
             }
            return language;
        }
    }

    /**
     * 参数选项
     * @param language 语言
     * @param ajax  异步请求
     * @param columns 表格列数据
     * @returns {{colReorder: boolean, dom: string, buttons: *[], select: boolean, pageLength: number, ordering: boolean, columns: *, searching: boolean, language: *, paging: boolean, lengthMenu: number[], ajax: {data: (function(*): *), dataType: string, type: string, url: *}, serverSide: boolean, fixedHeader: {headerOffset: jQuery}, autoWidth: boolean, lengthChange: boolean, processing: boolean, info: boolean}}
     * @private
     */
    var _paramOptions = function(params){

        var language = params.language;
        var columns = params.columns;
        var colReorder = params.colReorder;
        var ajax = params.ajax_params;

        if(language == "zh_CN"){
            language = _language.zh_CN();
        }else{
            language = _language.en_US();
        }
        var options = {
            destroy: true,
            language: language,//语言参数
            lengthMenu: [ [10, 25, 50, -1], [10, 25, 50, "全部"] ],//每页显示条数
            //pageLength : 5, //初始显示多少条
            paging: true,//是否允许表格分页
            lengthChange: true,//是否允许最终用户改变表格每页显示的记录数
            searching: false,//是否显示搜索框
            ordering: false,//是否显示排序
            info: true,//是否显示表格信息
            autoWidth: false,//自动计算表格宽度
            processing: true,//是否显示正在加载的状态
            serverSide: true,//是否通过服务端来获取数据
            ajax: {
                dataType: "json",
                type: "POST",
                url: ajax.url,
                data: function (d) {
                    var query_params = {};
                    query_params["draw"] = d.draw;
                    query_params.start = d.start;
                    query_params.length = d.length;
                    query_params.queryData = JSON.stringify(ajax.data);
                    console.info("ajax.data=="+JSON.stringify(ajax.data));
                    return query_params;//自定义需要传递的参数。
                }
            },//异步请求参数
            columns: columns,//列参数
            columnDefs: [
                {
                    "defaultContent": "",
                    "targets": "_all"
                }
            ],
            dom: "<'row'<'col-sm-12'f>B>" +
                "<'row'<'col-sm-12'tr>>" +
                "<'row'<'col-sm-3'l><'col-sm-3'i><'col-sm-6'p>>",//控件位置摆放
            buttons: [
                {
                    "extend": "pdf",
                    "text": "导出PDF",
                    "className": "btn_export_pdf", //按钮的class样式
                    "exportOptions": {
                        "modifier": {
                            "page": "current"
                        }
                    }
                },
                {
                    "extend": "csv",
                    "text": "导出csv",
                    "className": "btn_export_csv", //按钮的class样式
                    "exportOptions": {
                       "page":"current"
                    }
                },
                {
                    extend: 'excel',
                    "text": "导出excel",
                    "className": "btn_export_excel", //按钮的class样式
                    "exportOptions": {
                        "page":"current"
                    }
                },
                {
                    "extend": "print",
                    "text": '打印',
                    "className": "btn_export_print", //按钮的class样式
                    "exportOptions": {
                        "modifier": {
                            "page": "current"
                        }
                    }
                }
            ],//按钮参数,默认显示全选，和导出按钮，自定义按钮由使用者控制
            select: true,//是否选中一行
            fixedHeader: {
                headerOffset: $('#main-header').outerHeight()//锁定表头
            },
            colReorder: colReorder//控制位列置整调
        }
        if(params.fixedColumns == true){
            var siteColumns = params.siteColumns;
            var fixedSize = params.fixedSize;
            options["scrollX"] =  true;
            options["bScrollCollapse"] = true;
            options["fixedColumns"] = {
                siteColumns : fixedSize
            }
        }

        return options;
    }

    /**
     * 初始化按钮事件
     * @type {{init: init}}
     * @private
     */
    var _btn_events = {
        init:function(selector,callback){
            $(selector).on("click",function(e){
                if(callback)callback();
            });
        }
    };
    /**
     * 初始化按钮
     * @param selector table ID
     * @param custom_buttons 自定义按钮数据
     * @param default_buttons 默认按钮数据
     * @private
     */
    var _init_buttons = function(selector,custom_buttons,default_buttons){

        var add_button = '<button type="button" class="btn btn-box-tool" id="'+selector+'_btn_add"><i class="fa fa-fw fa-plus"></i>新增</button>';
        var edit_button = '<button type="button" class="btn btn-box-tool" id="'+selector+'_btn_edit"><i class="fa fa-fw fa-edit"></i>编辑</button>';
        var delete_button = '<button type="button" class="btn btn-box-tool" id="'+selector+'_btn_delete"><i class="fa fa-fw fa-close"></i>删除</button>';
        var select_button = '<div class="btn-group" id="'+selector+'_btn_select">' +
            '                   <button type="button" class="btn btn-box-tool"><i class="fa fa-fw fa-align-justify"></i>选择</button>' +
            '                   <button type="button" class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown">' +
            '                       <span class="caret"></span>' +
            '                   </button>' +
            '                   <ul class="dropdown-menu" role="menu">' +
            '                       <li><a href="#" id="'+selector+'_select_all">全选</a></li>' +
            '                       <li><a href="#" id="'+selector+'_select_none">全不选</a></li>' +
            '                   </ul>' +
            '                </div>';
        var export_button = '<div class="btn-group" id="'+selector+'_btn_export">' +
            '                   <button type="button" class="btn btn-box-tool"><i class="fa fa-fw fa-align-justify"></i>导出</button>' +
            '                   <button type="button" class="btn btn-box-tool dropdown-toggle" data-toggle="dropdown">' +
            '                       <span class="caret"></span>' +
            '                   </button>' +
            '                   <ul class="dropdown-menu" role="menu">' +
            '                       <li><a href="#" id="'+selector+'_export_pdf">导出PDF</a></li>' +
            '                       <li><a href="#" id="'+selector+'_export_csv">导出EXCEL</a></li>' +
            //'                       <li><a href="#" id="'+selector+'_export_excel">导出EXCEL</a></li>' +
            '                       <li class="divider"></li>' +
            '                       <li><a href="#" id="'+selector+'_export_print">打印</a></li>' +
            '                   </ul>' +
            '                 </div>';

        var html_buttons = "";

        default_btn_event = [];
        //生成默认按钮
        for(var i=0;i<default_buttons.length;i++){
            var item = {};
            //生成默认添加按钮
            if(default_buttons[i].add == false){
                html_buttons += add_button;
                item["id"] = "add";
                item["callback"] = default_buttons[i].callback;
                default_btn_event.push(item);
            };
            //生成默认编辑按钮
            if(default_buttons[i].edit == false){
                html_buttons += edit_button;
                item["id"] = "edit";
                item["callback"] = default_buttons[i].callback;
                default_btn_event.push(item);
            };
            //生成默认删除按钮
            if(default_buttons[i].delete == false){
                html_buttons += delete_button;
                item["id"] = "delete";
                item["callback"] = default_buttons[i].callback;
                default_btn_event.push(item);
            };
            //生成默认全选按钮
            if(default_buttons[i].select == false){
                html_buttons += select_button;
            };
            //生成默认导出按钮
            if(default_buttons[i].export == false){
                html_buttons += export_button;
            };
        }
        if(String.isEmpty(custom_buttons)){
            return false;
        }
        //生成自定义按钮
        var add_html = '<button type="button" class="btn btn-box-tool" id="%s_%s"><i class="fa fa-fw %s"></i>%s</button>';
        for(var i=0;i<custom_buttons.length;i++){
            html_buttons += String.stringFormat(add_html,selector,custom_buttons[i].id,custom_buttons[i].icons,custom_buttons[i].text);
        }

        //自定义按钮加入dom元素中
        $("#"+selector).parent().prepend(html_buttons);

    };
    /**
     * 初始化默认按钮绑定事件
     * @param tables  dataTables 对象，初始化后获取
     * @param selector table ID
     * @param de_btn 需要初始化事件的按钮，仅限增删改按钮，全选和导出不在此列
     * @private
     */
    var _btn_default_bind = function(tables,selector,de_btn){

        for(var i=0;i<de_btn.length;i++){
            var id_selector = "#%s_btn_%s";
            _btn_events.init(String.stringFormat(id_selector,selector,de_btn[i].id),de_btn[i].callback);
        };
        //全选
        $("#"+selector+"_select_all").on("click",function(){
            tables.rows().select();
        });
        //全不选
        $("#"+selector+"_select_none").on("click",function (){
            tables.rows().deselect();
        });
        //导出pdf
        $("#"+selector+"_export_pdf").on("click",function(){
            $(".btn_export_pdf").trigger("click");
        });
        //导出csv
        $("#"+selector+"_export_csv").on("click",function(){
            $(".btn_export_csv").trigger("click");
        });
        //导出 excel
        $("#"+selector+"_export_excel").on("click",function(){
            $(".btn_export_excel").trigger("click");
        });
        //打印
        $("#"+selector+"_export_print").on("click",function(){
            $(".btn_export_print").trigger("click");
        });
        //选中一列数据
        $("#"+selector+" thead tr").on("click","th", function () {
            tables.rows().deselect();
            //var obj = $(this);
            tables.columns().deselect();
            tables.columns($(this)).select();
        });
        //取消选中一列数据
        $("#"+selector+" thead tr").on("dblclick","th", function () {
            tables.columns().deselect();
        });
        $("#list_table tbody").on("click", "tr", function () {
            tables.columns().deselect();
        });

    }
    /**
     * 初始化自定义按钮绑定事件
     * @param selector table ID
     * @param custom_buttons  自定按钮参数
     * @private
     */
    var _btn_custom_bind = function(selector,custom_buttons){
        if(String.isEmpty(custom_buttons)){
            return false;
        }
        for(var i=0;i<custom_buttons.length;i++){
            var id_selector = "#%s_%s";
            _btn_events.init(String.stringFormat(id_selector,selector,custom_buttons[i].id), custom_buttons[i].callback);
        }
    }

    //dataTables初始化
    var dataTables_init = function(params,option_params){
        var tables;
        //创建dataTables
        if(!String.isEmpty(option_params)){
            tables = $("#"+params.id).DataTable(option_params);
        }else{
            tables = $("#"+params.id).DataTable(_paramOptions(params));
        }
        // //初始化按钮
        _init_buttons(params.id,params.buttons,params.default_buttons);
        // //自定义按钮绑定事件
        _btn_custom_bind(params.id,params.buttons);
        // //默认按钮绑定事件
        _btn_default_bind(tables,params.id,default_btn_event);
        return tables;
    }

    return {
        dataTables_init:dataTables_init
    }

});